<?php

namespace think\wework\Api;

use Psr\Http\Message\StreamInterface;
use think\wework\Abstracts\WeworkApiWithToken;

class Media extends WeworkApiWithToken
{
    private static ?Media $instance = null;
    public static function getInstance(): Media
    {
        if(!self::$instance instanceof Media) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    /**
     * 上传临时素材
     *
     * @param string $type
     * @param string $path
     * @return array
     */
    public function upload(string $type, string $path): array
    {
        $query = ['type'=>$type];
        return $this->httpClient->post('media/upload', array_merge([
            'multipart' => [
                [
                    'name' => 'media',
                    'contents' => fopen($path, 'r')
                ]
            ]
        ], compact('query')))->toArray();
    }

    /**
     * 获取临时素材
     *
     * @param string $id
     * @return StreamInterface
     */
    public function get(string $id): StreamInterface
    {
        $query = ['media_id' => $id];
        return $this->httpClient->get('media/get', compact('query'))->getBody();
    }

    /**
     * 获取高清语音素材
     *
     * @param string $id
     * @return StreamInterface
     */
    public function getVoice(string $id): StreamInterface
    {
        $query = ['media_id' => $id];
        return $this->httpClient->get('media/get/jssdk', compact('query'))->getBody();
    }

    /**
     * 上传图片
     *
     * @param string $path
     * @return array
     */
    public function uploadImg(string $path): array
    {
        return $this->httpClient->post('media/uploadimg', [
            'multipart' => [
                [
                    'name' => 'media',
                    'contents' => fopen($path, 'r')
                ]
            ]
        ])->toArray();
    }
}
